package com.wsjzzcbq.qianyuan.sys.service.impl;

import com.wsjzzcbq.qianyuan.common.bean.R;
import com.wsjzzcbq.qianyuan.common.constant.MsgConsts;
import com.wsjzzcbq.qianyuan.common.service.FileService;
import com.wsjzzcbq.qianyuan.common.util.DateUtils;
import com.wsjzzcbq.qianyuan.common.util.FileUtils;
import com.wsjzzcbq.qianyuan.common.util.SysUtils;
import com.wsjzzcbq.qianyuan.sys.service.SysFileService;
import com.wsjzzcbq.qianyuan.sys.vo.SysFileVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * SysFileServiceImpl
 *
 * @author wsjz
 * @date 2022/03/14
 */
@Service
public class SysFileServiceImpl implements SysFileService {

    @Value("${qianyuan.file.upload.path}")
    private String fileUploadPath;

    @Qualifier("localDrectoryFileServiceImpl")
    @Autowired
    private FileService fileService;

    @Override
    public R<SysFileVo> sysFileUpload(MultipartFile file) {
        if (file == null) {
            return R.error(MsgConsts.FILE_NOT_NULL);
        }

        String nowDateStr = DateUtils.nowDate(DateUtils.Pattern.YYYYMMDD);
        String fileType = FileUtils.getFileType(file.getOriginalFilename());
        String name = SysUtils.uuid();
        String fileName = name + fileType;

        String fileAddr = fileUploadPath + File.separator + nowDateStr + File.separator + fileName;

        fileService.upload(file, fileAddr);

        String url = "http://localhost/" + nowDateStr + "/" + fileName;

        SysFileVo vo = new SysFileVo();
        vo.setAddr(fileAddr);
        vo.setUrl(url);
        vo.setOriginalName(file.getOriginalFilename());
        vo.setName(name);
        vo.setFileName(fileName);
        vo.setFileType(fileType.substring(1));

        return R.success(vo);
    }


}
